package com.jungle.client.control;

import com.jungle.bfi.domain.vo.Option;
import com.jungle.client.event.SaveEvent;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableView;

import java.util.function.BiConsumer;

public class ComboBoxTableCell<S> extends TableCell<S, String> {
    private final ComboBox<Option> comboBox;

    public ComboBoxTableCell(ObservableList<Option> markerOptions, BiConsumer<S, Option> consumer) {
        comboBox = new ComboBox<>();
        comboBox.setItems(markerOptions);
        comboBox.setOnAction(event -> {
            // 更新数据模型
            int rowIndex = getIndex();
            TableView<S> tableView = getTableView();
            ObservableList<S> items = tableView.getItems();
            S dataItemVo = items.get(rowIndex);

            Option value = comboBox.getValue();
            consumer.accept(dataItemVo, value);

            //若数据已调置完整，触发保存操作
            Event.fireEvent(tableView, new SaveEvent(rowIndex));
            // 修改行
            items.set(rowIndex, dataItemVo);
        });
    }

    @Override
    protected void updateItem(String option, boolean empty) {
        super.updateItem(option, empty);
        if (empty) {
            setGraphic(null);
        } else {
            comboBox.setValue(toOption(option)); // 设置当前值
            setGraphic(comboBox);
        }
    }

    private Option toOption(String value) {
        return comboBox.getItems().stream().filter(option -> option.getValue().equals(value)).findAny().orElse(new Option(null, null));
    }
}

